package com.nantian.controller;

import com.nantian.entity.User;

import com.nantian.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import java.util.*;

@Controller
@RequestMapping("/user")
public class UserController {


    @Autowired
    private UserService userService;

    /**
     * 添加数据
     * @param name 用户名称
     * @param address 用户地址
     * @return
     */
    @RequestMapping(value = "/save",method = RequestMethod.GET)
    public ModelAndView save(@RequestParam("name") String name,@RequestParam("address") String address) {
        User user = new User();
        user.setName(name);
        user.setAddress(address);
        //生成一个随机ID,用于添加测试
        long random =new Double(Math.random()*1000).longValue();
        user.setUid(random);
        //时间
        user.setIntodate(new Date());
        //调用保存方法
        userService.save(user);
        //添加完成后,执行查询方法.跳转到展示页面
        ModelAndView mv = searchUser(0,50,"");
        return mv;
    }

    /**
     * 根据关键字查询
     * pageNumber 起始页码数
     * pageSize 每页记录数
     * searchContent 关键字
     */
    @GetMapping("/findUserByPage")
    @ResponseBody
    public ModelAndView searchUser(@RequestParam(value = "pageNumber",defaultValue = "0",required = false) int pageNumber,
                                 @RequestParam(value = "pageSize", required = false,defaultValue = "50") int pageSize,
                                 @RequestParam(value = "searchContent",required = false) String searchContent) {

        // 创建方法的返回值
        ModelAndView mv = new ModelAndView();
        Integer totalCount = 0;
        Integer totalPage = 0;
        // 开始计算pageIndex的边界值
        if(pageNumber > totalPage){
            pageNumber = totalPage;
        }
        if(pageNumber < 0){
            pageNumber = 0;
        }
        Page<User> userPage = userService.searchUser(pageNumber, pageSize, searchContent);

        //获取总记录数
        totalCount= new Integer((int)userPage.getTotalElements());
        // 计算总页数
        totalPage = totalCount%pageSize==0?totalCount/pageSize:
                totalCount/pageSize + 1;
        //获取结果集
        List<User> userList = userPage.getContent();
        // 保存数据
        mv.addObject("pageIndex",pageNumber);
        mv.addObject("pageSize",pageSize);
        mv.addObject("totalCount",totalCount);
        mv.addObject("totalPage",totalPage);
        mv.addObject("pageList",userList);
        // 设置展示页面
        mv.setViewName("user_list");
        // 返回
        return mv;
    }
}
